import { loginApi, getInfoApi, logoutApi } from "@/api/login";
import defAva from "@/static/image/profile/avatar.jpg";

export const useUserStore = defineStore(
  'user',
  () => {
    const token = ref(getToken());

    const user = ref<UserInfoRecord>(null);

    const avatar = ref("");

    const roles = ref<string[]>([]);

    /** 登录 */
    function login(userInfo: LoginFormRecord) {
      userInfo.username = userInfo.username.trim()
      userInfo.password = userInfo.password.trim()
      return loginApi(userInfo).then(response => {
        setToken(response.token)
        token.value = response.token
        return "";
      })
    }

    /** 获取用户信息 */
    function getInfo() {
      return getInfoApi().then(response => {
        user.value = response.user;
        roles.value = response.roles;
        const avatarUrl = !user.value.avatar ? defAva : import.meta.env.VITE_APP_BASE_API + user.value.avatar;
        if (response.roles && response.roles.length > 0) { // 验证返回的roles是否是一个非空数组
          roles.value = response.roles
        } else {
          roles.value = ['ROLE_DEFAULT']
        }

        avatar.value = avatarUrl

        return response;
      })
    }

    /** 退出系统 */
    function logOut() {
      return logoutApi(token.value).then(() => {
        user.value = null;
        token.value = '';
        avatar.value = '';
        roles.value = [];
        removeToken();
        return "";
      }).catch(err => {
        user.value = null;
        token.value = '';
        avatar.value = '';
        roles.value = [];
        removeToken();
        return "";
      })
    }

    return {
      token,
      user,
      avatar,
      roles,
      login,
      getInfo,
      logOut,
    }
  }
)